import { FC, useCallback, useEffect, useRef, useState } from "react";
import { wsIp } from "../../api/http";
import { LeftLogBox } from "../styled";

const LogBox:FC<{
    value:string
}> = ({value})=>{
    const [dataList,setDataList] = useState<any[]>([])
    const controlBoxRef = useRef<HTMLDivElement | null>(null);
    const ws = useRef<WebSocket | null>(null); //ws连接
    //建立ws连接
    const wsFun = useCallback(() => {
        let url = wsIp + `/junzheng/websocket/pcConsole?channelNo=${value}`;
            ws.current = new WebSocket(url);
            ws.current.onopen = (e) => {
                console.log('成功连接');
            }
            ws.current.onmessage = (e) => {
                let wsData = JSON.parse(e.data);
                console.log(wsData);
                setDataList(prevDataList => [...prevDataList, wsData]);
            }
        return () => {                    
            if (ws.current) {
                console.log(`Cleaning up WebSocket for channel ${value}`);
                ws.current.close();
                ws.current = null; // 确保 ws 引用被清空
            }
        };
    }, [value])

    useEffect(() => {
        if (controlBoxRef.current) {
            controlBoxRef.current.scrollTop = controlBoxRef.current.scrollHeight;
        }
    }, [dataList]);
    
    useEffect(() => {
        console.log(value,'value');
        
        // 清空数据并建立 WebSocket 连接
        setDataList([]);
        wsFun();
    }, [value, wsFun]);

    return(
        <LeftLogBox ref={controlBoxRef} >
            {dataList.length>0?
                dataList.map((item,index)=>{
                    return(
                        <div key={index} style={{display:'flex',marginTop:'5px'}}>
                            <div style={{width:'150px'}}>{item.time}</div>
                            <div style={{width:'500px'}}>{item.printlnMessage}</div>
                        </div>
                    )
                }):
                <div style={{marginLeft:'20px'}}>暂无日志</div>
            }
        </LeftLogBox>
    )
}

export default LogBox;